package com.sy.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.TimeUnit;


public class DateUtil {
    //针对时间
    public static Date addTime(int add, TimeUnit tu){
        Calendar calendar=Calendar.getInstance();

        switch (tu){
            case DAYS:calendar.add(Calendar.DAY_OF_MONTH,add);break;
            case MINUTES:calendar.add(Calendar.MINUTE,add);break;
            case SECONDS:calendar.add(Calendar.SECOND,add);break;
        }
        return calendar.getTime();
    }
    /**
     * 获取日期
     * @param add 要添加的日期
     * @param type 类型 1年  2月 3日*/
    public static Date addTime(int add, int type){
        Calendar calendar=Calendar.getInstance();

        switch (type){
            case 1:calendar.add(Calendar.YEAR,add);break;
            case 2:calendar.add(Calendar.MONTH,add);break;
            case 3:calendar.add(Calendar.DAY_OF_MONTH,add);break;
        }
        return calendar.getTime();
    }
    public static String getTime(){
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
    }

    public static String getDateM(){
        return new SimpleDateFormat("yyyy-MM").format(new Date());
    }

    //比较日期是否相同
    public static boolean checkDate(Date date,Date cdate){
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(date).equals(sdf.format(cdate));
    }

    //计算2个日期相差的天数
    public static long dateDays(Date date,Date cdate){
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        try {
            return (sdf.parse(sdf.format(cdate)).getTime()-sdf.parse(sdf.format(date)).getTime())/(24*60*60*1000);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0;
    }

    public static long dateDays(String date,String cdate){
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        try {
            return (sdf.parse(cdate).getTime()-sdf.parse(date).getTime())/(24*60*60*1000);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0;
    }
}